import { showToast } from "/utils/common.js";
//引入Promise js文件
const Promise = require('./plugins/es6-promise')
App({
  onLaunch(options) {
    if (dd.canIUse('getUpdateManager')) {
      const updateManager = dd.getUpdateManager()

      updateManager.onCheckForUpdate(function (res) {
        console.log(res.hasUpdate) // 是否有更新
      })

      updateManager.onUpdateReady(function (ret) {
        dd.confirm({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success: function (res) {
            if (res.confirm) {
              updateManager.applyUpdate()
            }
          }
        })
      })
      updateManager.onUpdateFailed(function () {
        // 新版本下载失败
      })
    }
  },
  getSystemInfoMethod() {
    return new Promise((resolve, reject) => {
      dd.getSystemInfo({
        success: e => {
          this.globalData.systemInfo = e;
          resolve(e)
        },
        fail: () => {
          showToast({ msg: "获取手机设备信息失败!" })
          reject()
        }
      })
    })
  },
  // 钉钉小程序 免登陆
  getAuthCodeMethod() {
    return new Promise((resolve, reject) => {
      dd.getAuthCode({
        success: res => {
          // login--接口
          dd.httpRequest({
            url: `${this.globalData.omsDomain}/web/user/login?username=${res.authCode}&password=authCode`,
            dataType: "json",
            method: "post",
            success: (res) => {
              if (res.status === 200 && res.data.success) {
                // if (res.headers['Set-Cookie'].length === 2) {
                //   this.globalData.cookie = res.headers['Set-Cookie'][0].split('; ')[0] + '; '
                // }
                this.globalData.cookie += 'Authenticator=' + res.data.vo.dingUserId
                this.globalData.cookie += '; userName=' + res.data.vo.userName
                this.globalData.cookie += '; avatar=' + res.data.vo.avatar
                this.globalData.cookie += '; dingOrgId=' + res.data.vo.dingOrgId
                this.globalData.cookie += '; dingOrgName=' + res.data.vo.dingOrgName
                this.globalData.userInfo = res.data.vo;
                this.globalData.permissions = res.data.vo.menuTreeNode.children ? this.getPermissions(res.data.vo.menuTreeNode) : [];
                this.getCrmUserInfo().then(res => {
                  this.globalData.userInfo.dpid = res.vo.dpid
                  this.globalData.userInfo.useAgent = res.vo.useAgent && JSON.parse(res.vo.useAgent);
                  this.setSystemInfo();
                  resolve()
                }).catch(err => {
                  reject()
                })
              } else {
                showToast({ msg: res.data.messages[0] })
              }
            },
            fail: (err) => {
              showToast("登录失败！login失败");
              reject(err);
            },
            complete: () => {
              dd.hideLoading()
            }
          })
        },
        fail: err => {
          console.log(err)
        }
      })
    })
  },
  getCrmUserInfo() {
    return new Promise((resolve, reject) => {
      dd.httpRequest({
        url: `${this.globalData.domain}/api/crm/user/getUserInfo`,
        method: 'get',
        headers: {
          Cookie: encodeURI(this.globalData.cookie)
        },
        dataType: "json",
        success: (res) => {
          if (res.status === 200 && res.data.success) {
            resolve(res.data)
          } else {
            showToast({ msg: res.data.messages[0] })
            reject(res.data.messages[0])
          }
        },
        fail: (err) => {
          reject(err);
        }
      })
    })
  },
  setSystemInfo() {
    dd.httpRequest({
      url: `${this.globalData.domain}/api/crm/user/setSystemInfo`,
      method: "post",
      headers: {
        Cookie: encodeURI(this.globalData.cookie),
        "Content-Type": "application/json"
      },
      data: JSON.stringify({ systemInfo: this.globalData.systemInfo }),
    })
  },
  getPermissions(tree) {
    let arr = [];
    arr.push(tree.key);
    if (tree.children && tree.children.length) {
      for (let i = 0; i < tree.children.length; i++) {
        let result = this.getPermissions(tree.children[i]);
        arr.push(...result);
      }
    }
    return arr;
  },
  // 获取用户人员架构列表
  getUnderUserList() {
    return new Promise((resolve, reject) => {
      if (this.globalData.underUserList === null) {
        dd.showLoading({
          content: '加载中...'
        })
        dd.httpRequest({ // 查询当前人下子级数量（>1有子级可以转出同事 1 || 0没有子级）
          url: `${this.globalData.omsDomain}/ding/getByCodeAndDingUserId`,
          method: "get",
          data: {
            code: "saleFramework",
            dingUserId: this.globalData.userInfo.dingUserId
          },
          success: (res) => {
            dd.hideLoading()
            if (res.status === 200 && res.data.success) {
              this.globalData.underUserList = res.data.voList;
              resolve(res.data.voList);
            } else {
              showToast({ msg: res.data.messages[0] })
              reject()
            }
          },
          fail: function (err) {
            dd.hideLoading()
            showToast({
              msg: "请求错误:" + JSON.stringify(err)
            })
            reject(err);
          }
        })
      } else {
        resolve(this.globalData.underUserList)
      }
    })
  },
  globalData: {
    // production
    domain: "https://crm.doqtech.com.cn",
    omsDomain: "https://oms.doqtech.com.cn",
    uploadUrl: "https://fs.doqtech.com.cn/filesystem/crm/ajax/upload/file",
    // development
    // omsDomain: "https://omstest.doqtech.com.cn",
    // domain: "https://crmtest.doqtech.com.cn",
    // domain: "http://192.168.1.106:8098",
    // uploadUrl: "https://fs.doqtech.com.cn/test/filesystem/crm/ajax/upload/file",
    permissions: [],
    userInfo: null,
    token: "",
    cookie: "",
    systemInfo: null,
    underUserList: null
  }
});
